// pages/voteResult/voteResult.js
import { reLogin } from '../../service/request'
import activityApi from '../../service/activityApi'
import sweepstakeApi from '../../service/sweepstakeApi'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hadAuthFlag: false,
    loadingFlag: false,
    showCompleteFlag: false,
    rewardType: app.globalData.codeConfig.rewardType,
    couponList: [],
    sourceList: [],
    showSharePopFlag: false,
    showRegimentRules: false, // 拼团规则弹窗
    shareLoading: false,
    rewardMultiple: '0',
    userId: '',
    teamName: '',
    couponType: app.globalData.codeConfig.couponType,
    sourcePage: 'vote'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.page) {
      this.setData({
        sourcePage: options.page
      })
      if (options.page === 'detail') {
        this.setData({
          teamName: options.teamName,
          teamNo: options.teamNo
        })
      }
    }
    this.checkStatus()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 授权状态的检查
  checkStatus () {
    let that = this
    // 判断是否有授权，有授权的话从回调调用方法初始化数据
    // 无授权的话直接调用方法初始化数据
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            hadAuthFlag: true
          })
          if (wx.getStorageSync('token')) {
            that.getCouponList()
          } else {
            app.checkStatusCallback = res => {
              that.setData({
                userInfo: res,
                hasUserInfo: true
              })
              that.getCouponList()
            }
          }
        } else {
          that.getCouponList()
        }
      }
    })
  },
  getCouponList () {
    let that = this
    that.setData({
      loadingFlag: true
    })
    activityApi.rewardCoupon({
      rewardType: that.data.rewardType.VOTE
    }).then((res) => {
      that.setData({
        loadingFlag: false
      })
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        console.log(1)
        that.setData({
          sourceList: [...res.data.data.couponList]
        })
        that.handleTicketOperate(that.data.sourceList, false)
      }
    }).catch((res) => {
      console.log(1)
      that.setData({
        loadingFlag: false
      })
    })
  },
  // 显示拼团规则弹窗 
  onShowRegimentRules() {
    this.setData({
      showRegimentRules: true
    })
  },
  // 关闭拼团规则弹窗
  closeRegimentRules() {
    this.setData({
      showRegimentRules: false
    })
  },
  // 获取用户信息回调
  bindGetUserInfo (e) {
    let that = this
    // that.showConfrimLoading()
    console.log(e.detail.userInfo)
    if (!!e.detail.userInfo) { // 同意授权-并登陆
      wx.setStorageSync('hadAuthFlag', true)
      app.globalData.userInfo = e.detail.userInfo
      app.globalData.hadAuthUserInfo = true
      reLogin().then(() => {
        // that.hideConfrimLoading()
        that.setData({
          hadAuthFlag: true
        })
        // that.handleConfirmBuy()
        console.log(app.globalData.userInfo)
      }).catch((res) => {
        // that.hideConfrimLoading()
      })
    } else { // 不同意授权
      // that.hideConfrimLoading()
      wx.setStorageSync('hadAuthFlag', false)
      that.setData({
        hadAuthFlag: false
      })
    }
  },
  // 打开分享弹窗
  handleShowSharePop () {
    if (!this.data.hadAuthFlag) return
    this.getRewardMultiple()
  },
  // 关闭分享弹窗
  handleCloseSharePop () {
    this.setData({
      showSharePopFlag: false
    })
  },
  // 获取中奖倍率
  getRewardMultiple () {
    let that = this
    if (that.data.shareLoading) return
    that.setData({
      shareLoading: true
    })
    wx.showLoading({
      title: '',
      mask: true
    })
    sweepstakeApi.getRewardMultiple().then((res) => {
      that.setData({
        shareLoading: false
      })
      wx.hideLoading()
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        that.setData({
          rewardMultiple: res.data.data.multiple,
          userId: res.data.data.userId
        })
        if (that.data.rewardMultiple === '0') {
          wx.showToast({
            icon: 'none',
            title: '请先进行投票操作，初始化中奖倍率'
          })
        } else {
          that.setData({
            showSharePopFlag: true
          })
        }
      }
    }).catch((res) => {
      wx.hideLoading()
      that.setData({
        shareLoading: false
      })
    })
  },
  // 立即使用
  handleToUseTicket () {
    if (this.data.loadingFlag) return
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  // 隐藏部分卡券
  handleTicketOperate (list, showFlag = false) {
    let that = this
    if (showFlag) {
      that.setData({
        couponList: [...list]
      })
    } else {
      that.setData({
        couponList: list.length > 1 ? [...list.slice(0, 1)] : [...list]
      })
    }
  },
  // 切换是否显示全部卡券
  handleToggleComplete () {
    let that = this
    that.setData({
      showCompleteFlag: !that.data.showCompleteFlag
    })
    that.handleTicketOperate(that.data.sourceList, that.data.showCompleteFlag)
  },

  // 去任务列表
  goTaskList () {
    wx.navigateTo({
      url: '/pages/task/task'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    that.setData({
      showSharePopFlag: false
    })
    return {
      title: that.data.sourcePage === 'vote' ? '投票、领券、抽大奖——600元全额抵扣券哦~' : `“${that.data.teamName}”战队需要您的一票之力！可领600元全额抵扣券！`,
      imageUrl: app.globalData.picBaseUrl + '/vote/20190506/mzR2vJap7IWC.png',
      path: that.data.sourcePage === 'vote' ? '/pages/index/index?targetPage=vote&userId=' + that.data.userId : '/pages/index/index?targetPage=teamDetail&userId=' + that.data.userId + '&teamNo=' + that.data.teamNo
    }
  }
})